package com.utils;

import com.framework.util.Utils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * 文件和base64字符互转
 */
public class FileUtils {

    /**
     * 文件转base64数据
     * @param file
     * @return
     */
    public static String fileToBase64(File file){
        String encode = "";
        try{
            FileInputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            encode = new BASE64Encoder().encode(buffer);
            encode = encode.replaceAll("\r\n", "");
            encode = encode.replace("\n", "");
            inputFile.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return encode;
    }

    /**
     * base64数据转文件
     * @param path
     * @param fileName
     * @param base64Buffer
     * @return
     */
    public static File base64ToFile(String path,String fileName,String base64Buffer){
        File file = null;
        try {
            if (base64Buffer == null) //图像数据为空
                return null;
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = decoder.decodeBuffer(base64Buffer);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成jpeg图片
            String imgFilePath = path+File.separator+fileName;//新生成的图片
            Utils.addFile(path);
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            System.out.println("create photo success："+imgFilePath);
            file = new File(imgFilePath);
        }catch (Exception e){
            e.printStackTrace();
        }
        return file;
    }

    public static void main(String[] args){

        String baseStr = "";
        File file = FileUtils.base64ToFile("d:\\","abc.png",baseStr);
        System.out.println(file.getName());
//        File file = new File("F:\\cardolar\\picture\\goods\\1\\5eaa6b0d-1a68-4038-a46e-02f10f6136aa.jpg");
//        System.out.println(fileToBase64(file));
    }
}
